package test;

import akka.actor.ActorRef;
import akka.actor.Actors;
import akka.serialization.ActorSerialization;
import akka.serialization.RemoteActorSerialization;
import akka.serialization.RemoteTypedActorSerialization;

import java.io.*;

/**
 * NetworkActorRef -
 */
public class NetworkActorRef implements Serializable {
  private ActorRef actorRef;

  public NetworkActorRef(ActorRef actorRef) {
    this.actorRef = actorRef;
  }

  public ActorRef getActorRef() {
    return actorRef;
  }

  private void writeObject(ObjectOutputStream out) throws IOException {
    byte[] asByte = RemoteActorSerialization.toRemoteActorRefProtocol(actorRef).toByteArray();

    DataOutputStream dataOutputStream = new DataOutputStream(out);
    dataOutputStream.writeInt(asByte.length);
    out.write(asByte);
  }

  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    DataInputStream dataInputStream = new DataInputStream(in);
    int length = dataInputStream.readInt();

    byte[] asByte = new byte[length];
    int readLength = in.read(asByte);

    if(readLength == length) {
      actorRef = (ActorRef)RemoteActorSerialization.fromBinaryToRemoteActorRef(asByte);
    } else {
      throw new IOException("Not enough bytes were read.");
    }
  }
}
